package com.briup.security.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangzh
 */
public class JwtUtil {

    /**
     * 过期时间 单位:毫秒
     */
    private static final long EXPIRE_TIME =   30 * 60 * 1000;

    private static final String SECRET = "security_jwt";

    public static final String TOKEN_HEAD = "TOKEN";

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 签发 token
     * @param userId 用户信息
     * @param info 用户自定义信息
     * @return
     */
    public static String sign(String userId, Map<String,Object> info) {
        // 设置过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        // 设置加密算法
        Algorithm hmac512 = Algorithm.HMAC512(SECRET);
        return JWT.create()
                    .withAudience(userId) // 将用户id放入到token中
                    .withClaim("info",info) // 自定义用户信息
                    .withExpiresAt(date) // 设置过期时间
                    .sign(hmac512);

    }

    /**
     * 从token中获取userId
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            return JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 从token中获取自定义信息
     * @param token
     * @return
     */
    public static Map<String,Object> getInfo(String token) {
        try {
            Claim claim = JWT.decode(token).getClaim("info");
            return claim.asMap();
        } catch (JWTDecodeException e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC512(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            logger.info("token 无效:" + e.getMessage());
            throw new RuntimeException("token无效，请重新获取");
        }

    }



}
